package com.gill.demo;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @Description: zookeeper ip认证的acl的demo演示
 */
public class ZKNodeAclIP implements Watcher {

	private ZooKeeper zookeeper = null;

	public static final String zkServerPath = "env:2181";
	public static final Integer timeout = 5000;

	public ZKNodeAclIP() {}

	public ZKNodeAclIP(String connectString) {
		try {
			zookeeper = new ZooKeeper(connectString, timeout, new ZKNodeAclIP());
		} catch (IOException e) {
			e.printStackTrace();
			if (zookeeper != null) {
				try {
					zookeeper.close();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
	
	public void createZKNode(String path, byte[] data, List<ACL> acls) {
		
		String result = "";
		try {
			result = zookeeper.create(path, data, acls, CreateMode.PERSISTENT);
			System.out.println("创建节点：\t" + result + "\t成功...");
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
	}
	
	public static void main(String[] args) throws Exception {
	
		ZKNodeAclIP zkServer = new ZKNodeAclIP(zkServerPath);

		// ip方式的acl
//		List<ACL> aclsIP = new ArrayList<ACL>();
//		Id ipId1 = new Id("ip", "1.1.1.1");//若zk服务端部署在外网则ip必须是公网IP
//		aclsIP.add(new ACL(ZooDefs.Perms.ALL, ipId1));
//		zkServer.createZKNode("/aclimooc/ip", "ip".getBytes(), aclsIP);

		zkServer.getZookeeper().setData("/aclimooc/ip", "new-ip".getBytes(),2);
		Stat stat = new Stat();
		byte[] data = zkServer.getZookeeper().getData("/aclimooc/ip", false, stat);
		System.out.println(new String(data));//获取修改后的数据

	}

	public ZooKeeper getZookeeper() {
		return zookeeper;
	}
	public void setZookeeper(ZooKeeper zookeeper) {
		this.zookeeper = zookeeper;
	}

	@Override
	public void process(WatchedEvent event) {
		
	}
}

